﻿@page "/saleorder"
@using System.Collections.ObjectModel
@inject DialogService DialogService
@inject ISaleOrderService SaleOrderService
@inject ISaleOrderDetailService SaleOrderDetailService

<RadzenText TextStyle="TextStyle.H4">销售单</RadzenText>
<PageTitle>销售单</PageTitle>
<RadzenStack Style="display: flex; margin: 0px 10px 10px 0px" Orientation="Orientation.Horizontal" JustifyContent="JustifyContent.Start" AlignItems="AlignItems.Center">
    <RadzenDatePicker @bind-Value=@startDatetime @onchange:preventDefault Name="RadzenDatePickerBindValue" ShowCalendarWeek />
    <RadzenDatePicker @bind-Value=@endDatetime @onchange:preventDefault Name="RadzenDatePickerBindValue" ShowCalendarWeek />
    <RadzenTextBox @bind-Value="@keyword" Placeholder="客户名" Style="margin:10px 0px 10px 0px" />
    <RadzenButton Text="查询" Icon="refresh" @onclick:stopPropagation Click=@(args => Search()) ButtonStyle="ButtonStyle.Primary" />
    <RadzenButton Text="新增" Icon="add_circle" Click=@(args => Add()) ButtonStyle="ButtonStyle.Primary" />
</RadzenStack>

<RadzenDataGrid EmptyText="暂无数据"
                Data="@Data"
                @bind-Value=@selectedOrders
                GridLines="@Radzen.DataGridGridLines.Default"
                AllowPaging="true"
                AllowSorting="true"
                SelectionMode="DataGridSelectionMode.Single"
                FilterCaseSensitivity="FilterCaseSensitivity.CaseInsensitive">
    <Columns>
        <RadzenDataGridColumn Property="Id" Title="序号" Width="100px" TextAlign="TextAlign.Center" />
        <RadzenDataGridColumn Property="" Title="操作">
            <Template Context="data">
                <RadzenStack Gap="10" Style="margin-bottom: 10px" Orientation="Orientation.Horizontal">
                    <RadzenButton Text="修改" @onclick:stopPropagation Click="@(args => Update(data))" ButtonStyle="ButtonStyle.Primary" />
                    <RadzenButton Text="删除" @onclick:stopPropagation Click="@(args => Delete(data))" ButtonStyle="ButtonStyle.Danger" />
                </RadzenStack>
            </Template>
        </RadzenDataGridColumn>
        <RadzenDataGridColumn Property="Code" Title="编号" />
        <RadzenDataGridColumn Property="Name" Title="名称" />
        <RadzenDataGridColumn Property="Customer.Name" Title="客户名称" />
        <RadzenDataGridColumn Property="CreatedAt" Title="创建时间">
            <Template Context="data">
                @data.CreatedAt.ToString("D")
            </Template>
        </RadzenDataGridColumn>
        <RadzenDataGridColumn Property="Remark" Title="备注" />
    </Columns>
</RadzenDataGrid>

<RadzenDataGrid Style="margin-top:15px;"
                EmptyText="暂无数据"
                Data="@details"
                GridLines="@Radzen.DataGridGridLines.Default"
                AllowPaging="true"
                AllowSorting="true"
                SelectionMode="DataGridSelectionMode.Single"
                FilterCaseSensitivity="FilterCaseSensitivity.CaseInsensitive">
    <Columns>
        <RadzenDataGridColumn Property="Id" Title="序号" Width="100px" TextAlign="TextAlign.Center" />
        <RadzenDataGridColumn Property="" Title="操作">
            <Template Context="data">
                <RadzenStack Gap="10" Style="margin-bottom: 10px" Orientation="Orientation.Horizontal">
                    <RadzenButton Text="删除" @onclick:stopPropagation Click="@(args => DeleteDetail(data))" ButtonStyle="ButtonStyle.Danger" />
                </RadzenStack>
            </Template>
        </RadzenDataGridColumn>
        <RadzenDataGridColumn Property="Product.Code" Title="产品编号" />
        <RadzenDataGridColumn Property="Product.Name" Title="产品名称" />
        <RadzenDataGridColumn Property="UnitPrice" Title="单价" />
        <RadzenDataGridColumn Property="Quantity" Title="数量" />
        <RadzenDataGridColumn Property="TotalPrice" Title="总价" />
        <RadzenDataGridColumn Property="CreatedAt" Title="创建时间">
            <Template Context="data">
                @data.CreatedAt.ToString("D")
            </Template>
        </RadzenDataGridColumn>
        <RadzenDataGridColumn Property="Remark" Title="备注" />

    </Columns>
</RadzenDataGrid>

@code {
    IList<SaleOrder> selectedOrders;
    private IList<SaleOrderDetail> details {
        get 
        {
            if (selectedOrders == null || selectedOrders.Count == 0)
            {
                return new List<SaleOrderDetail>();
            }
            return selectedOrders[0].Details; 
        } 
    }
    private string keyword = string.Empty;
    private DateTime startDatetime { get; set; } = DateTime.Now;
    private DateTime endDatetime { get; set; } = DateTime.Now;
    ObservableCollection<SaleOrder> Data = new ObservableCollection<SaleOrder>();

    private void OnRowSelected(object order)
    {
        StateHasChanged();
    }

    private void Search()
    {
        var list = SaleOrderService.Search(new BaseInput()
        {
            keyword = keyword,
            sdate = startDatetime,
            edate = endDatetime
        });
        Data = new ObservableCollection<SaleOrder>(list);
    }

    private async void Add()
    {
        var order = new SaleOrder();
        SaleOrder result = await DialogService.OpenAsync<SaleOrderAddDialog>(
            $"新增销售单",
            new Dictionary<string, object>() { { "POrder", order } },
            new DefaultDialogOptions(width: "1600px", height: "1312px"));

        if (result != null)
        {
            SaleOrderService.LoadData(result);
            //var newOrder = SaleOrderService.Get(result.Id);
            //Data!.Add(newOrder!);
            Data!.Add(result);
        }
    }

    private async void Update(SaleOrder selectedItem)
    {
        SaleOrder result = await DialogService.OpenAsync<SaleOrderAddDialog>(
            $"修改销售单",
            new Dictionary<string, object>() {{"POrder", selectedItem}},
            new DefaultDialogOptions(width: "1600px", height: "1312px"));
                      
        if (result != null)
        {
            StateHasChanged();
        }
    }
    private async void Delete(SaleOrder selectedItem)
    {
        var result = await DialogService.Confirm("确认要删除吗?", "提示", new ConfirmOptions()
        {
            OkButtonText = "确定",
            CancelButtonText = "取消"
        });

        if ((bool)result)
        {
            try
            {
                SaleOrderService.Delete(selectedItem.Id);
                Data!.Remove(selectedItem);
                if (Data.Count > 0)
                {
                    selectedOrders = new List<SaleOrder>()
                    {
                        Data[0]
                    };
                }
                else
                {
                    selectedOrders = new List<SaleOrder>();
                }
                StateHasChanged();
            }
            catch (Exception e)
            {
                await DialogService.Alert(e.Message, "错误", new AlertOptions() { OkButtonText = "确定" });
            }
        }
    }
    
    public async void DeleteDetail(SaleOrderDetail detail)
    {
        var result = await DialogService.Confirm("确认要删除吗?", "提示", new ConfirmOptions()
        {
            OkButtonText = "确定",
            CancelButtonText = "取消"
        });
        if ((bool)result)
        {
            try
            {
                SaleOrderDetailService.Delete(detail.Id);
                if (selectedOrders != null && selectedOrders.Count > 0)
                {
                    selectedOrders[0].Details.Remove(detail);
                }
            }
            catch (Exception e)
            {
                await DialogService.Alert(e.Message, "错误", new AlertOptions() { OkButtonText = "确定" });
            }
        }
    }

    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();

        var input = new BaseInput()
        {
            keyword = keyword,
            sdate = startDatetime,
            edate = endDatetime
        };
        var list = SaleOrderService.Search(input);
        Data = new ObservableCollection<SaleOrder>(list);
        if (Data.Count > 0)
        {
            selectedOrders = new List<SaleOrder>()
            {
                Data[0]
            };
        }
    }

}
